<template>
  <component
    is="a-modal"
    v-model:visible="visible"
    :width="600"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit"
  >
    <a-spin :loading="spinLoading" tip="权限列表加载中，请稍后···" style="margin:0 auto;width:100%;">
      <!-- 表单信息 start -->
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :auto-label-width="true"
      >
        <a-form-item label="角色名称" field="name">
          <a-input v-model="formData.name" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="权限" field="rule">
          <sa-tree-slider
            v-model="formData.rule" 
            :field-names="{key:'rule_id',title:'name'}"
            :data="roleTree"
            :border="true"
            searchPlaceholder="请输入权限名称"
            @click="chooseRole"
          >

          </sa-tree-slider>
        </a-form-item>

        <a-form-item label="操作密码" field="admin_pay_password">
          <a-input-password
            v-model="formData.admin_pay_password"
            placeholder="请输入"
          />
        </a-form-item>
        <a-form-item label="谷歌验证码" field="google_code">
          <a-input v-model="formData.google_code" placeholder="请输入" />
        </a-form-item>
      </a-form>
      <!-- 表单信息 end -->
    </a-spin>
  </component>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { Message } from "@arco-design/web-vue";
import systemApi from "@/api/system/system";
import SaTreeSlider from '@cps/sa-treeSlider/index.vue'
import { throttle } from "lodash";
const roleTree = ref([]);
const emit = defineEmits(["success"]);
// 引用定义
const formRef = ref();
const mode = ref("");
const visible = ref(false);
const loading = ref(false);
const spinLoading=ref(false)
let title = computed(() => {
  return "角色组" + (mode.value == "add" ? "-新增" : "-编辑");
});
// 表单信息
const formData = reactive({
  name: "",
  rule:[],
  admin_pay_password: "",
  google_code: "",
  id: "",
});

// 验证规则
const rules = ref({
  name: [{ required: true, message: "请输入" }],
  rule: [{ required: true, message: "请输入" }],
  admin_pay_password: [{ required: true, message: "请输入" }],
  google_code: [{ required: true, message: "请输入" }],
});
// 打开弹框
const open = async (type = "add",data) => {
  visible.value = true;
  mode.value = type;
  formRef.value.resetFields();
  spinLoading.value=true
  roleTree.value=[]
  if (type == "add") {
     getTree();
  }else{//权限这一块最好还是让后端重写逻辑 之前php的逻辑不适合现在vue3的任何系统  现在是前端硬写 硬匹配的 - -
    formData.id=data.id
     getTree(data.id);
  }
};
const chooseRole=(e,data)=>{
  
}
const getTree = async (id='') => {
  const { data } = await systemApi.getRoleTree({id:id});
  roleTree.value=await buildTreeOptimized(data.list);
  if(mode.value!='add'){
    console.log('扁平化后的樹',roleTree.value);
    formData.rule = updateCheckedNodes(roleTree.value, data.checkedId);
  }
  
  
};

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key];
    }
  }
};

// 数据保存
const submit = throttle(async (done) => {
  const validate = await formRef.value?.validate();
  if (!validate) {
    loading.value = true;
    try {
      let data = { ...formData };
      console.log('data',data);
      let result = {};
      if (mode.value === "add") {
        // 添加数据
        data.id = undefined;
        result = await systemApi.createRole(data);
      } else {
        // 修改数据
        result = await systemApi.updateRole(data);
      }
      if (result.code === 200) {
        Message.success("操作成功");
        emit("success");
        done(true);
      }
      // 防止连续点击提交
      setTimeout(() => {
        loading.value = false;
      }, 500);
    } catch {
      loading.value = false;
    }
  }
  done(false);
}, 100);

// 关闭弹窗
const close = () => (visible.value = false);
// 將数组扁平化
const buildTreeOptimized = (data) => {
  const map = new Map();
  const tree = [];
  data.forEach((item) => {
    map.set(item.rule_id, { ...item, children: [] });
  });

  // 第二次遍历，构建树形结构
  data.forEach((item) => {
    if (item.pid === 0) {
      tree.push(map.get(item.rule_id));
    } else {
      const parent = map.get(item.pid);
      if (parent) {
        parent.children.push(map.get(item.rule_id));
      }
    }
  });
  spinLoading.value=false
  return tree;
};
//遞歸剔除父節點
const updateCheckedNodes = (tree, checked) => {
  tree.forEach((node) => {
    // 递归更新子节点的选中状态
    if (node.children && node.children.length > 0) {
      // 递归检查子节点的选中状态
      updateCheckedNodes(node.children, checked);

      // 检查该节点的所有子节点是否全部被选中
      const allChildrenChecked = node.children.every(child => checked.includes(child.rule_id));

      if (allChildrenChecked) {
        // 如果所有子节点都被选中，保留父节点
        if (!checked.includes(node.rule_id)) {
          checked.push(node.rule_id);
        }
      } else {
        // 如果任何子节点没有选中，移除父节点
        const parentIndex = checked.indexOf(node.rule_id);
        if (parentIndex !== -1) {
          checked.splice(parentIndex, 1);
        }
      }
    }

    // 如果该节点本身被选中，检查其父节点的选中状态
    if (checked.includes(node.rule_id) && node.pid !== 0) {
      // 获取父节点
      const parentNode = tree.find(item => item.rule_id === node.pid);
      if (parentNode && !checked.includes(parentNode.rule_id)) {
        // 如果父节点不在选中列表中，添加父节点
        checked.push(parentNode.rule_id);
      }
    }
  });
  return checked;
};
defineExpose({ open, setFormData });
</script>
